<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods,i) in goodsList" :key="i" @click="gotoGoodsDetail(goods.goods_id)">
        <my-goods :goods="goods"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        queryObj: {
          query: '', //查询关键词
          cid: '', //分类ID
          pagenum: 1, //页数索引
          pagesize: 10 //每页长度
        },
        goodsList: [], //商品列表数据
        total: 0,
        isloading: false
      };
    },
    onLoad(options) {
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      // 获取商品列表数据
      this.getGoodsList()
    },
    methods: {
      async getGoodsList(callback) {
        // 开启节流阀
        this.isloading = true
        const {
          data: res
        } = await uni.$http.get('/goods/search', this.queryObj)
        if (res.meta.status !== 200) return uni.$ShowMsg()
        // 关闭节流阀
        this.isloading = false

        // 只要数据请求完毕，就立即按需调用 cb 回调函数
        callback && callback()

        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
      },
      // 跳转至商品详情页
      gotoGoodsDetail(id) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + id
        })
      }
    },
    // 上拉加载
    onReachBottom() {
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$ShowMsg('数据已全部加载！')

      if (this.isloading) return
      // 页码自增1
      this.queryObj.pagenum += 1
      this.getGoodsList()
    },
    // 下拉刷新
    onPullDownRefresh() {
      // 重置重要数据
      this.queryObj.pagenum = 1
      this.total = 0
      this.isloading = false
      this.goodsList = []
      // 重新获取商品列表
      this.getGoodsList(() => uni.stopPullDownRefresh())
    }
  }
</script>

<style lang="scss">

</style>